import cherrypy
import sha
from django.utils import simplejson

from app.models import PayDetails, Benefit
from app.controllers.benefit import BenefitController
from app.controllers.payroll import PayrollController
from app.controllers.employee import EmployeeController
from app.dutil import toClass

from google.appengine.ext import db

class BenefitHandler:
	@cherrypy.expose
	def index(self):
		pass
		
	# @cherrypy.expose
	# def employee(self, benefitId=None):
		# if benefitId is not None:
			# rsEmployees = EmployeeController.getEmployeesByBenefit(benefitId)
			# dEmployee = dict([('page',1), ('rows',[rEmployee.toCells() for rEmployee in rsEmployees])])
			# dEmployee.update(total=len(dEmployee['rows']))
			# return simplejson.dumps(dEmployee)
		
	@cherrypy.expose	
	def benefits(self, *args, **kwargs):
		columns = ["name","amount","descr","perc","deduct","taxable","active"]
		rsBenefits = BenefitController.getBenefits()
		dBenefits = dict([('page',1), ('rows',[rBenefit.toCells(columns) for rBenefit in rsBenefits])])
		dBenefits.update(total=len(dBenefits['rows']))
		return simplejson.dumps(dBenefits)
		
	@cherrypy.expose
	def vbenefit(self,id=None):
		try:
			rsBenefit = BenefitController.getBenefit(int(id))
			dBenefit = rsBenefit.toRow()
			return simplejson.dumps(dBenefit)
		except TypeError:
			return None
	
	@cherrypy.expose
	def list(self):
		rsBenefits = BenefitController.getBenefits()
		dBenefits = [rBenefit.toRows(['name']) for rBenefit in rsBenefits]
		return simplejson.dumps(dBenefits)
		
	@cherrypy.expose
	def ubenefit(self, *args, **kwargs):
		if kwargs:
			brs = BenefitController.updateBenefit(toClass(kwargs))
		else: brs = False
			
		return simplejson.dumps(dict([('success',brs)]))
	
	@cherrypy.expose
	def abenefit(self, *args, **kwargs):
		if kwargs:
			brs = BenefitController.addBenefit(toClass(kwargs))
		else: brs = False
			
		return simplejson.dumps(dict([('success',brs)]))
	
	@cherrypy.expose
	def dbenefit(self, id=None):
		if id is not None:
			brs = BenefitController.deleteBenefit(id)
		else: brs = False
		
		return simplejson.dumps(dict([('success',brs)]))



		
	